﻿using CubicFWNet.Data.Models;
using CubicFWNet.Data.SystemManager;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CubicFWNet.Application.SystemManager
{
    public class RoleApp
    {
        private RoleRepository _roleRepository;
        private RelevanceRepository _relevanceRepository;
        public RoleApp()
        {
            _relevanceRepository = new RelevanceRepository();
            _roleRepository = new RoleRepository();
        }

        public Role GetForm(Guid id)
        {
            return _roleRepository.FindEntity(id);
        }

        public IEnumerable<Role> Load(int pageindex, int pagesize)
        {
            var roles = _roleRepository.Find(pageindex, pagesize);
            var total = roles.Count();
            return roles;
        }

        public IEnumerable<Role> Load()
        {
            return _roleRepository.IQueryable().OrderBy(a => a.SortNo);
        }

        /// <summary>
        /// 加载一个角色的全部 模块Ids
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<Guid> Load(Guid roleId)
        {
            List<Guid> modules = new List<Guid>();
            if (roleId == Guid.Empty)
            {
                return modules;
            }
            return _roleRepository.LoadByRoleId(roleId).ToList();
        }

        public void AddOrUpdate(Role role, string[] moduleIds)
        {
            if (role.Id == Guid.Empty)
            {
                role.Id = Guid.NewGuid();
                _roleRepository.Insert(role);
            }
            else
            {
                _roleRepository.Update(role);
            }
            //更新用户的模块
            var secIds = moduleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            var type = "RoleModule";
            _relevanceRepository.DeleteBy("RoleModule", role.Id);
            _relevanceRepository.AddRelevance(type, secIds.ToLookup(u => role.Id));
        }


        public void Delete(Guid id)
        {
            _roleRepository.Delete(a => a.Id == id);
        }


    }
}
